//
//  HZJTreeTab.swift
//  HZJTreeView
//
//  Created by 何治军 on 2020/6/18.
//  Copyright © 2020 何治军. All rights reserved.
//

import UIKit

class HZJTreeTab: UITableView {
    
    /// 设置数据
    /// - Parameter data: <#data description#>
    func setData(_ data:[HZJTreeViewModelProtocol]) {
        self.data = data
        self.updateUI()
    }
    
    @discardableResult
    func setHeader(_ view:UIView) -> HZJTreeTab{
        self.tableHeaderView = view
        return self
    }
    
    @discardableResult
    func setFooter(_ view:UIView) ->HZJTreeTab{
        self.tableFooterView = view
        return self
    }
    
    init(_ data:[HZJTreeViewModelProtocol] = [], style: UITableView.Style = .plain) {
        super.init(frame: CGRect(), style: style)
        self.backgroundColor = .white
        self.register(HZJTreeCell.self, forCellReuseIdentifier: String(describing: HZJTreeCell.self))
        self.dataSource = self
        self.delegate = self
        self.separatorStyle = .none
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 原始传入数据
    fileprivate var data:[HZJTreeViewModelProtocol] = []
    
    /// 展示用的数据
    private var showData:[HZJTreeViewModelProtocol] = []
}

extension HZJTreeTab:UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return showData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: HZJTreeCell.self), for: indexPath) as? HZJTreeCell {
            let model = self.showData[indexPath.row]
            cell.model = model
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: UITableViewCell.self), for: indexPath)
            cell.backgroundColor = .red
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.showData[indexPath.row]
        model.changeChildModelShowState(!model.isOpen, allChild: false)
        self.updateUI()
    }
}

private extension HZJTreeTab {
    func updateUI() {
        self.showData = self.data.getAllShowTreeData()
        self.reloadData()
    }
}
